package leetcode_2101_2200;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class LeeCode_2195 {
    public static void main(String[] args) {
        System.out.println(minimalKSum(new int[]{1, 4, 25, 10, 15}, 2));
        System.out.println(minimalKSum(new int[]{5,6}, 3));
        System.out.println(minimalKSum(new int[]
                {96,44,99,25,61,84,88,18,19,33,60,86,52,19,32,47,35,50,94,17,29,98,22,21,72,100,40,84}, 35));
        System.out.println(getSum(1, 3));
    }
    private static long minimalKSum(int[] nums, int k) {
        Arrays.sort(nums);
        Set<Integer> set = new HashSet<>();
        int pre = 0;
        long ans = 0;
        for (int num : nums) {
            if (set.contains(num))
                continue;
            set.add(num);
            int count = num - pre - 1;
            if (count == 0) {
                pre = num;
                continue;
            }
            if (count < k) {
                ans += getSum(pre + 1, num - 1);
                k -= count;
            } else {
                ans += getSum(pre + 1, pre + k);
                k = 0;
                break;
            }
            pre = num;
        }
        if (k > 0){
            ans += getSum(pre + 1, pre + k);
        }
        return ans;
    }
    private static long getSum(int l, int r){
        long ans = (long) (l + r) * ((r - l + 1) / 2);
        if (((r - l + 1 ) & 1) == 1){
            ans += (l + r) / 2;
        }
        return ans;
    }
}